<!--  -->
<template>
  <div class='authority'>
    <el-button type="primary" v-permissions="'user:add'" @click="addUser" style="margin-bottom: 10px;">新增</el-button>
    <el-form :inline="true" :model="formInUser" class="demo-form-inline">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="formInUser.value1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="模糊查询关键字">
        <el-input v-model="formInUser.kw" placeholder="请输入关键字"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInUser.status" placeholder="请选择状态">
          <el-option label="正常" value="1"></el-option>
          <el-option label="封禁" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否过期">
        <el-select v-model="formInUser.isExpire" placeholder="请选择是否过期">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSrearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        :data="getUserList"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="身份"
          width="120">
          <template slot-scope="scope">
            <span @click="showPopDetailRule" class="detailRuleCls">{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="到期时间"
          width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="是否到期"
          width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.isExpire === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.status === 1 ? '正常' : '封禁' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          >
          <template slot-scope="scope">
            <el-button v-permissions="'user:detail'" @click="getRoleDetail(scope.row.id,scope.row.roleName)" type="text" size="small">详情</el-button>
            <!-- <el-button @click="setRoleDetail(scope.row.id,scope.row.roleName)" type="text" size="small">修改</el-button> -->
            <el-button v-permissions="'user:delete'" @click="deletRoleUser(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog
        title="用户详情"
        :close-on-click-modal="false"
        :show-close="false"
        :close-on-press-escape="true"
        :visible.sync="dialogVisible"
        width="50%">
        <el-form
          ref="basicForm"
          :model="updatedUser"
          :disabled="isDisabled"
          :inline="false"
          class="demo-form-inline"
          label-position="left"
          :rules="upDateUserRule"
          label-width="auto">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="updatedUser.name"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="updatedUser.userName"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="updatedUser.phone"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="updatedUser.status" placeholder="请选择状态">
                <el-option
                v-for="(item,index) in statusArr"
                :key="index"
                :label="item.name"
                :value="item.status"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleid">
              <el-select v-model="updatedUser.roleName" placeholder="请选择状态" @change="changeListRole">
                <el-option
                  v-for="(item,index) in addUserList"
                  :key="index"
                  :label="item.roleName"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="过期时间" prop="expireTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="updatedUser.expireTime" style="width: 100%;" :default-value="parseTime(updatedUser.expireTime)"></el-date-picker>
            </el-form-item>
        </el-form>
        <div class="buttons">
           <el-button type="primary" @click="setConfigUserRole" v-if="isDisabled">修改</el-button>
           <el-button type="primary" @click="submitConfigUser" v-if="!isDisabled">保存</el-button>
           <el-button @click="closeDiaDetail">关闭</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="新增用户"
        :visible.sync="addUserShow"
        @close="closeDia"
        :close-on-press-escape="true"
        :close-on-click-modal="false"
        width="50%">
        <el-form ref="formName" :model="formAddUser" :rules="addUserRule" label-width="80px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formAddUser.name"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="formAddUser.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="passWord">
            <el-input v-model="formAddUser.passWord"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formAddUser.phone"></el-input>
          </el-form-item>
          <el-form-item label="到期时间" prop="expireTime">
            <el-date-picker type="date" placeholder="选择日期" v-model="formAddUser.expireTime" style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="状态" prop="statusId">
            <el-select v-model="formAddUser.statusId" placeholder="请选择状态">
              <el-option label="封禁" value="0"></el-option>
              <el-option label="正常" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="formAddUser.roleId" placeholder="请选择角色">
              <el-option
                v-for="(item, index) in addUserList"
                :key="index"
                :label="item.roleName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="width: 100%; text-align: center;">
          <el-button type="primary" @click="addRoleUser">保存</el-button>
        </div>
      </el-dialog>
      <!-- 抽屉 -->
      <el-drawer
        title="角色权限详情"
        :visible.sync="drawerShowNow"
        :direction="direction">
        <span>我来啦!</span>
      </el-drawer>
    </div>
    <pagination
      class="pagination_container"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="getUserListInit"
    />
  </div>
</template>

<script>
import { userRoleList, userAdd, userList, userDelete, userDetail, userUpdate } from '@/api/adduser'
import { parseTime } from '@/until/paramRou'
import Pagination from '@/components/pagination'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    Pagination
  },
  data () {
    // 这里存放数据
    return {
      drawerShowNow: false,
      direction: 'rtl',
      setUpdateRoleId: '', // 修改用户详情的角色ID
      statusArr: [
        {
          status: 1,
          name: '正常'
        },
        {
          status: 0,
          name: '封禁'
        }
      ],
      isDisabled: true,
      updatedUser: { // 修改用户
        name: '',
        roleName: '',
        userName: '',
        expireTime: '',
        phone: '',
        id: '',
        roleid: '',
        status: ''
      },
      upDateUserRule: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        status: [
          { required: true, trigger: 'change', message: '请选择状态' }
        ],
        roleid: [
          { required: true, trigger: 'change', message: '请选择角色' }
        ],
        expireTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的用户名' }
        ]
      },
      getUserList: [], // 用户列表
      addUserList: [], // 角色列表
      formAddUser: {
        name: '',
        passWord: '',
        phone: '',
        statusId: '',
        roleId: [],
        expireTime: '',
        userName: '',
        setUpdateRoleIdInList: ''
      },
      // 新增 rule 验证
      addUserRule: {
        name: [
          { required: true, trigger: 'blur', message: '请输入您的名字' }
        ],
        passWord: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
          { min: 6, max: 12, message: '长度为6-12位', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入您的手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        statusId: [
          { required: true, trigger: 'change', message: '请选择状态' }
        ],
        roleId: [
          { required: true, trigger: 'change', message: '请选择角色' }
        ],
        expireTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的用户名' }
        ]
      },
      // 分页
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 查询
      formInUser: {
        value1: [],
        kw: '',
        isExpire: '',
        status: ''
      },
      // checked: false,
      dialogVisible: false,
      userNameGet: '',
      userRoleIdGet: null,
      userRemarkGet: '',
      userList: JSON.parse(sessionStorage.getItem('routerList')),
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultCheckRole: [],
      setRoleIdArrFir: [],
      setRoleIdArrSen: [],
      addUserShow: false,
      form: {
        roleName: '',
        remark: ''
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 展示权限
    showPopDetailRule () {
      // this.drawerShowNow = true
    },
    handleClose () {},
    // closeDiaDetail
    closeDiaDetail () {
      this.dialogVisible = false
      this.isDisabled = true
    },
    // 获取用户列表
    getUserListInit () {
      if (
        this.formInUser.value1 === null ||
        this.formInUser.value1[1] === undefined ||
        this.formInUser.value1[0] === undefined) {
        userList({
          endTime: '',
          startTime: '',
          isExpire: isNaN(parseInt(this.formInUser.isExpire)) || this.formInUser.isExpire === null ? '' : parseInt(this.formInUser.isExpire),
          status: isNaN(parseInt(this.formInUser.status)) || this.formInUser.status === null ? '' : parseInt(this.formInUser.status),
          kw: this.formInUser.kw,
          limit: this.pagination.pageSize,
          page: this.pagination.page
        }).then(res => {
          if (res.code === '200') {
            this.getUserList = res.data.records
            if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
              this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
              this.getUserListInit()
            } else {
              this.pagination.total = res.data.total
            }
          } else {
            this.$message({
              message: res.message,
              type: 'warning'
            })
          }
        })
      } else {
        userList({
          endTime: parseTime(this.formInUser.value1[1]),
          startTime: parseTime(this.formInUser.value1[0]),
          isExpire: this.formInUser.isExpire,
          status: this.formInUser.status,
          kw: this.formInUser.kw
        }).then(res => {
          if (res.code === '200') {
            this.getUserList = res.data.records
            if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
              this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
              this.getUserListInit()
            } else {
              this.pagination.total = res.data.total
            }
          } else {
            this.$message({
              message: res.message,
              type: 'warning'
            })
          }
        })
      }
    },
    // 获取角色列表
    getUserRoleList () {
      userRoleList().then(res => {
        if (res.code === '200') {
          this.addUserList = res.data
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      })
    },
    // 打开新增弹框
    addUser () {
      this.addUserShow = true
      this.getUserRoleList()
    },
    // 新增保存
    addRoleUser () {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          this.formAddUser.expireTime = new Date(this.formAddUser.expireTime).getTime()
          userAdd(this.formAddUser).then(res => {
            this.addUserShow = false
            if (res.code === '200') {
              this.getUserListInit()
              this.$message({
                message: '操作成功',
                type: 'success'
              })
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 查询
    submitSrearch () {
      this.getUserListInit()
    },
    // 重置
    resetForm () {
      this.formInUser.value1 = []
      this.formInUser.kw = ''
      this.formInUser.isExpire = ''
      this.formInUser.status = ''
    },
    // 删除用户
    deletRoleUser (val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        userDelete(val).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getUserListInit()
          } else {
            this.$message({
              type: 'info',
              message: res.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 用户详情
    getRoleDetail (val, name) {
      this.userNameGet = name
      this.userRoleIdGet = val
      userDetail(val).then(res => {
        this.updatedUser = res.data
        this.updatedUser.id = res.data.id
        this.updatedUser.setUpdateRoleIdInList = res.data.roleId
        this.dialogVisible = true
      })
    },
    // 修改用户详情
    setConfigUserRole () {
      this.$confirm('是否确认修改用户信息', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        distinguishCancelAndClose: false
      }).then(() => {
        this.isDisabled = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消!'
        })
      })
    },
    // 选择角色下拉选
    changeListRole (val) {
      this.setUpdateRoleId = val
    },
    // 保存修改后用户信息
    submitConfigUser () {
      const role = {
        expireTime: new Date(this.updatedUser.expireTime).getTime(),
        id: this.updatedUser.id,
        name: this.updatedUser.name,
        phone: this.updatedUser.phone,
        roleId: this.setUpdateRoleId || this.updatedUser.setUpdateRoleIdInList,
        status: this.updatedUser.status,
        userName: this.updatedUser.userName
      }
      console.log(role)
      userUpdate(role).then(res => {
        if (res.code === '200') {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.isDisabled = true
          this.getUserListInit()
        } else {
          this.$message({
            type: 'info',
            message: res.message
          })
        }
      })
    },
    closeDia () {
      this.formAddUser = {}
    },
    roleNodeChange (checkedNodes, data) {
      this.setRoleIdArrFir = data.checkedKeys
      this.setRoleIdArrSen = data.halfCheckedKeys
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getUserRoleList() // 获取角色列表
    this.getUserListInit()
    // this.getRouterList()
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
.authority {
  width: 100%;
  height: 100%;
}
.fir {
  width: auto;
  height: 30px;
  line-height: 30px;
  span {
    margin-left: 10px;
    padding: 5px;
    width: 30%;
  }
}
.sen {
  margin: 5px auto;
  width: 80%;
  padding: 10px;
  border: 1px solid #f0f0f0;
}
.buttons {
  width: 100%;
  text-align: center;
}
.detailRuleCls {
  // color: #FF00FF;
  cursor:pointer;
}
</style>
